<?php
/**
 * php 请求http
 * 其他方法
 * @see http://www.jb51.net/article/51974.htm
 * Created by PhpStorm.
 * User: XD
 * Date: 2017/8/30
 * Time: 17:27
 */

function get_html_one()
{
    //方法1: 用file_get_contents 以get方式获取内容
    $url = 'https://www.baidu.com';
    $html = file_get_contents($url);
    echo $html;
}

function get_html_two()
{
    //使用用fopen打开url, 以get方式获取内容：
    $url = 'https://www.baidu.com';
    $fp = fopen($url, 'r');
    stream_get_meta_data($fp);
    $result = null;
    while (!feof($fp)) {
        $result .= fgets($fp, 1024);
    }
    echo "url body:$result";
    fclose($fp);
}

function post_html_one()
{
    //方法3：用file_get_contents函数,以post方式获取url
    $data = array('foo' => 'bar');
    $data = http_build_query($data);

    $opts = array(
        'http' => array(
            'method' => 'POST',
            'header' => "Content-type: application/x-www-form-urlencodedrn" .
                "Content-Length:" . strlen($data) . "rn",
            'content' => $data
        )
    );

    $context = stream_context_create($opts);
    $html = file_get_contents("http://localhost/e/admin/test.html", false, $context);
    echo $html;

}

//function get_html_three($url, $cookie=false){
//方法4：用fsockopen函数打开url，以get方式获取完整的数据，
//包括header和body,fsockopen需要 PHP.ini 中 allow_url_fopen 选项开启
{
function get_url($url, $cookie = false)
{
    $url = parse_url($url);
    $query = $url[path] . "?" . $url[query];
    echo "Query:" . $query;
    $fp = fsockopen($url[host], $url[port] ? $url[port] : 80, $errno, $errstr, 30);
    if (!$fp) {
        return false;
    } else {
        $request = "GET $query HTTP / 1.1rn";
        $request .= "Host: $url[host]rn";
        $request .= "Connection: Closern";
        if ($cookie) {
            $request .= "Cookie:  $cookie";
        }
        $request .= "rn";
        fwrite($fp, $request);
        $result = "";
        while (!@feof($fp)) {
            $result .= @fgets($fp, 1024);
        }
        fclose($fp);
        return $result;
}
}

//获取url的html部分，去掉header
    function GetUrlHTML($url, $cookie = false)
    {
        $rowdata = get_url($url, $cookie);
        if ($rowdata) {
            $body = stristr($rowdata, "rnrn");
            $body = substr($body, 4, strlen($body));
            return $body;
        }
        return false;
    }
}


get_html_two();


?>